package cn.ljy.mes.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.mes.dao.mapper.MesCarModelConfigMapper;
import cn.ljy.mes.dao.mapper.ShopCarProductMapper;
import cn.ljy.mes.dao.mapper.ShopCustomerMapper;
import cn.ljy.mes.model.ShopCarOrder;
import cn.ljy.mes.model.ShopCarProduct;
import cn.ljy.mes.model.ShopCustomer;
import cn.ljy.mes.model.common.MesConstant;
import cn.ljy.mes.model.query.ShopCarOrderQuery;
import cn.ljy.mes.service.ShopCarOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Date;

@Service
public class IShopCarOrderService extends IBaseService<ShopCarOrder, ShopCarOrderQuery> implements ShopCarOrderService {

    @Autowired
    private ShopCustomerMapper customerMapper;
    @Autowired
    private ShopCarProductMapper carProductMapper;
    @Autowired
    private MesCarModelConfigMapper carModelConfigMapper;
    @Override
    protected void enrichEntityFields(ShopCarOrder shopCarOrder){
        if(shopCarOrder!=null){

        }
    }

    @Override
    protected void beforeSave(ShopCarOrder shopCarOrder) {
        //验证产品信息
        if(shopCarOrder.getCarProduct().getId()==null){
            throw new MyWebException("验证失败：产品id不能为空");
        }
        //获取客户信息
        if(shopCarOrder.getCustomer().getId()==null){
            throw new MyWebException("验证失败：客户id不能为空");
        }
        //根据汽车产品信息获得对应信息
        ShopCarProduct carProduct=carProductMapper.findById(shopCarOrder.getCarProduct().getId());
        if(carProduct!=null){
            shopCarOrder.setCarModelConfig(carProduct.getCarModelConfig());//获取配置信息
            shopCarOrder.setOriginalPrice(carProduct.getOriginalPrice());//获取指导价
            shopCarOrder.setPromotionPrice(carProduct.getPrice());//获取成交价
        }else{
            throw new MyServiceException("验证失败：产品记录不存在，请刷新后重试！");
        }
        //根据客户信息填充订单信息
        ShopCustomer customer=customerMapper.findById(shopCarOrder.getCustomer().getId());
        if(customer!=null){
            if(shopCarOrder.getDeliveryName()==null){
                if(StringUtils.hasLength(customer.getName())){
                    shopCarOrder.setDeliveryName(customer.getName());
                }else{
                    throw new MyServiceException(String.format("验证失败：账户%s的姓名为空，请补充后再提交订单！",customer.getUsername()));
                }
            }
            if(shopCarOrder.getDeliveryTel()==null){
                if(StringUtils.hasLength(customer.getTel())){
                    shopCarOrder.setDeliveryTel(customer.getTel());
                }else{
                    throw new MyServiceException(String.format("验证失败：账户%s的电话为空，请补充后再提交订单！",customer.getUsername()));
                }
            }
            if(shopCarOrder.getDeliveryZip()==null){
                if(StringUtils.hasLength(customer.getZip())){
                    shopCarOrder.setDeliveryZip(customer.getZip());
                }else{
                    throw new MyServiceException(String.format("验证失败：账户%s的邮编为空，请补充后再提交订单！",customer.getUsername()));
                }
            }
            if(shopCarOrder.getDeliveryAddress()==null){
                if(StringUtils.hasLength(customer.getAddress())){
                    shopCarOrder.setDeliveryAddress(customer.getAddress());
                }else{
                    throw new MyServiceException(String.format("验证失败：账户%s的地址为空，请补充后再提交订单！",customer.getUsername()));
                }
            }
        }else{
            throw new MyServiceException("验证失败：客户信息不存在，请刷新后重试！");
        }
        //创建id号
        shopCarOrder.setId(IdUtil.simpleUUID());
        //订单状态,第一次下单未待支付状态。
        shopCarOrder.setOrderStatus("pending");
    }

    @Override
    protected void beforeUpdate(ShopCarOrder shopCarOrder) {
        //编辑的时候不能直接修改订单状态，订单状态只能在专用函数changeStatus修改
        ShopCarOrder carOrderOrignl=mapper.findById(shopCarOrder.getId());
        if(carOrderOrignl==null){
            throw new MyServiceException("验证失败：系统中不存在订单信息，请刷新后重试");
        }
        if(!shopCarOrder.getOrderStatus().equals("pending")&&!shopCarOrder.getOrderStatus().equals("paid")){
            throw new MyServiceException("验证失败：订单已经确认，不能再修改订单信息");
        }
    }

    @Override
    public void changeStatus(String orderId, String targetStatus) {
        if(!MesConstant.SHOPCARORDER_OPRATORSTATUSMAP.contains(targetStatus)){
            throw new MyWebException("验证失败：订单操作状态值错误，无法被系统识别！");
        }
        ShopCarOrder carOrder=mapper.findById(orderId);
        if(carOrder==null){
            throw new MyServiceException("验证失败：系统中不存在订单信息，请刷新后重试");
        }
        boolean allowUpdate=false;//是否允许修改
        //处理订单信息，后期需要加日志等功能
        if(targetStatus.equals("paid")){//如果是客户支付订单
            if(carOrder.getOrderStatus().equals("pending")){//如果为待支付状态
                carOrder.setOrderStatus(targetStatus);
                carOrder.setPaymentTime(new Date());//设置支付时间
            }else{
                throw new MyServiceException("订单状态变更失败：订单无法支付！");
            }
        }else if(targetStatus.equals("confirmed")){//如果是商家确认订单
            if(carOrder.getOrderStatus().equals("paid")){//如果为已支付状态
                carOrder.setOrderStatus(targetStatus);
                carOrder.setConfirmedTime(new Date());//设置商家确认时间
            }else{
                throw new MyServiceException("订单状态变更失败：订单只有支付后商家才能确认！");
            }
        }else if(targetStatus.equals("shipped")){//如果是要发货
            if(carOrder.getOrderStatus().equals("produced")){//如果为已生产完成状态
                carOrder.setOrderStatus(targetStatus);
                carOrder.setShippedTime(new Date());//设置商家确认时间
            }else{
                throw new MyServiceException("订单状态变更失败：汽车没有完成生产，无法发货！");
            }
        }else if(targetStatus.equals("completed")){//如果是要确认收货，完成订单
            if(carOrder.getOrderStatus().equals("shipped")){//如果为已生产完成状态
                carOrder.setOrderStatus(targetStatus);
                carOrder.setShippedTime(new Date());//设置商家确认时间
            }else{
                throw new MyServiceException("订单状态变更失败：汽车没有发货，无法确认收货！");
            }
        }else if(targetStatus.equals("cancelled")){//如果是要取消
            if(carOrder.getOrderStatus().equals("paid")||carOrder.getOrderStatus().equals("confirmed")){//如果是确认阶段（未生产前），商家可以取消订单
                carOrder.setOrderStatus("cancelled");
                carOrder.setCancelledType("merchant_cancelled");//设置取消类型
                carOrder.setCancelledTime(new Date());//设置取消时间
            }else{
                throw new MyServiceException("订单状态变更失败：订单无法取消，如确定要取消请联系系统管理员");
            }
        }else if(targetStatus.equals("customerCancelled")){//如果是要取消
            if(carOrder.getOrderStatus().equals("pending")){//如果是准备阶段，客户可以取消订单
                carOrder.setOrderStatus("cancelled");
                carOrder.setCancelledType("customer_cancelled");//设置取消类型
                carOrder.setCancelledTime(new Date());//设置取消时间
            }else{
                throw new MyServiceException("订单状态变更失败：订单无法取消，如确定要取消请联系系统管理员");
            }
        }
        //保存订单状态
        mapper.update(carOrder);

    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        throw new MyServiceException("操作失败：订单无法删除");
    }
}
